import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { Socket, io } from 'socket.io-client';
import { baseURL } from '@/utils/request';
import { getAuth } from '@/utils/storage';

type MsgType = {
  msg: string;
  type: string;
  timestamp: number;
}[];
export default function Chat() {
  const clientRef = useRef<Socket | null>(null);
  const [list, setList] = useState([] as MsgType);
  const [msg, setMsg] = useState('');
  const handleSendMsg = () => {
    if (!msg.trim()) {
      return;
    }
    //1. 发送给服务器
    clientRef.current?.emit('message', { msg, type: 'user', timestamp: Date.now() });
    //2. 将用户输入的内容，添加到列表中
    setList([...list, { msg, type: 'user', timestamp: Date.now() }]);
    //3. 清空输入框
    setMsg('');
  };
  useEffect(() => {
    // 创建客户端
    clientRef.current = io(baseURL, {
      transports: ['websocket'],
      query: {
        token: getAuth()?.token,
      },
    });
    // 建立连接
    clientRef.current.on('connect', () => {
      console.log('连接成功');
      setList([{ msg: '你好，我是小智同学', type: 'robot', timestamp: Date.now() }]);
    });
    // 监听收到消息的事件
    clientRef.current.on('message', (data) => {
      console.log('>>>>收到 socket.io 消息:', data);
      setList((prevList) => {
        return [...prevList, { ...data, type: 'robot' }];
      });
    });

    return () => {
      //关闭链接
      clientRef.current?.close();
    };
  }, []);
  //接收最新数据滚动到底部
  useEffect(() => {
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    });
  }, [list]);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list">
        {list.map((item) => {
          return (
            <div key={item.timestamp} className={classNames('chat-item', { user: item.type === 'user' })}>
              {item.type === 'robot' ? (
                <Icon type="iconbtn_xiaozhitongxue" />
              ) : (
                <img src={'http://toutiao.itheima.net/images/user_head.jpg'} alt="" />
              )}

              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        {/* 底部消息输入框 */}
        <div className="input-footer">
          <Input
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            className="no-border"
            placeholder="请描述您的问题"
          />
          <Icon type="iconbianji" />
          <span onClick={handleSendMsg} className="send">
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
